package com.mmz.javaapi;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class CreateNodeDemo implements Watcher{
    private static String CONNECTSTRING = "192.168.44.130:2181,192.168.44.131:2181,192.168.44.132:2181";
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static Stat stat = new Stat();
    private static ZooKeeper zooKeeper ;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
         zooKeeper = new ZooKeeper(CONNECTSTRING, 5000, new CreateNodeDemo());
       countDownLatch.await();
        if(zooKeeper.exists("/node",true)==null){
            String result = zooKeeper.create("/node","123".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
        }

        zooKeeper.getData("/node",new CreateNodeDemo(),stat);
//        zooKeeper.setData("/node","321".getBytes(),-1);
//
//
//        zooKeeper.delete("/node",-1);

        zooKeeper.create("/node/node1","123".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){

            if(watchedEvent.getType() == Event.EventType.None){
                countDownLatch.countDown();
//                System.out.println(watchedEvent.getState()+"   "+watchedEvent.getType());

            }
            if(watchedEvent.getType() == Event.EventType.NodeCreated){// 监听不到
                System.out.println("节点"+watchedEvent.getPath()+"创建");
                try {
                    zooKeeper.getData(watchedEvent.getPath(),true,stat);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else if(watchedEvent.getType() == Event.EventType.NodeDataChanged){
                System.out.println("节点"+watchedEvent.getPath()+"值发生改变");
                try {
                    zooKeeper.getData(watchedEvent.getPath(),true,stat);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else if(watchedEvent.getType() == Event.EventType.NodeDeleted){
                System.out.println("节点"+watchedEvent.getPath()+"删除");
                try {
                    zooKeeper.getData(watchedEvent.getPath(),true,stat);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
